﻿using MayEditor.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using OpenAI_API;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static MayEditor.Startup;

namespace MayEditor.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public async Task GetStreamedString(string prompt,string chatId)
        {
            string apiKey = AppSetting.GetAppSetting("APIkey");
            string answer = string.Empty;
            var api = new OpenAIAPI(apiKey);
            var chat = api.Chat.CreateConversation();
            api.ApiUrlFormat = AppSetting.GetAppSetting("OpenAIUrl");
            chat.Model = AppSetting.GetAppSetting("ChatModel");
            var response = HttpContext.Response;
            response.ContentType = "text/plain";
            chat.AppendUserInput(prompt);
            string responsea = "";
            var writer = new StreamWriter(response.Body, Encoding.UTF8, -1, true);
            await foreach (var res in chat.StreamResponseEnumerableFromChatbotAsync())
            {
                responsea += res;
                await writer.WriteAsync(res);
                await writer.FlushAsync();
                //return Ok(new { data = res, chatId = chatId, success = true });
            }
            var finishi = new
            {
                isfinishi = true,
            };
            writer.Write(chatId);
            await writer.FlushAsync();
            await writer.DisposeAsync();

        }
    }
}
